package org.hxzon.cyclone.pfgen;

import org.hxzon.cyclone.Particle;
import org.hxzon.cyclone.Util;
import org.hxzon.cyclone.Vector3;

//弹簧力发生器
public class ParticleSpring implements ParticleForceGenerator {
    /** The particle at the other end of the spring. */
    private Particle other;

    //弹簧系数
    private double springConstant;

    //弹簧自然长度
    private double restLength;

    public ParticleSpring(Particle other, double springConstant, double restLength) {
        this.other = other;
        this.springConstant = springConstant;
        this.restLength = restLength;
    }

    public void updateForce(Particle particle, double duration) {
        {
            // 位移向量
            Vector3 force = particle.getPosition().copy();
            force.minusUpdate(other.getPosition());

            // 弹簧形变长度
            double magnitude = force.magnitude();
            magnitude = Util.realAbs(magnitude - restLength);

            // 弹簧力公式，胡克定律
            magnitude *= springConstant;
            force.normalise();
            force.multiUpdate(-magnitude);
            particle.addForce(force);
        }
    }

}
